package com.ynet.middleground.approve.model;

import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Component;

import com.google.common.base.Throwables;
import com.ynet.core.common.ServiceResult;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.core.util.IDUtil;
import com.ynet.middleground.contract.bean.QueryTemplatesConditionReq;
import com.ynet.middleground.contract.service.TemplateService;

/**
 * @author liulx
 * @description 合约中心模块服务调用模块
 * @date 2020-07-09 14:37
 */
@Component
public class ContractCenterModel {

    @Reference(version = "0.0.1")
    private TemplateService templateService;

    /**
     * 判断模板是否可以变更为其他状态
     *
     * @param templateIds 模板 id 列表
     * @param statusCode 模板目标状态
     * @param channel 渠道
     * @param operationUserId 操作人
     */
    public void checkTemplateCondition(List<Integer> templateIds, String statusCode, String channel,
        Integer operationUserId) {
        QueryTemplatesConditionReq req = new QueryTemplatesConditionReq();
        req.setTemplateIds(templateIds);
        req.setStatusCode(statusCode);

        req.setTraceId(IDUtil.getSecureRandomId());
        req.setChannel(channel);
        req.setOperationUserId(operationUserId);
        req.setRequestTime(new Date());
        ServiceResult<Object> serviceResult;
        try {
            serviceResult = templateService.checkTemplateCondition(req);
        } catch (BusinessException e) {
            throw new BusinessException(e.getMessage(), e.getCode());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "合约中心服务调用失败,case:{}",
                Throwables.getStackTraceAsString(e));
            throw new BusinessException("合约中心服务调用失败", "ECAP0005");
        }
        getServiceResult(serviceResult);
    }

    /**
     * 获取 ServiceResult 结果值
     *
     * @param serviceResult 服务返回结果对象
     * @param <T> 返回对象数据中具体的数据类型
     * @return ServiceResult 结果值
     */
    private <T> T getServiceResult(ServiceResult<T> serviceResult) {
        Optional.ofNullable(serviceResult).orElseThrow(() -> new BusinessException("合约中心服务调用失败", "ECAP0005"));
        if (serviceResult.isSuccess()) {
            return serviceResult.getResult();
        }
        throw new BusinessException(serviceResult.getErrorMsg(), serviceResult.getErrorCode());
    }

}
